package com.yimi.yinhepda.db.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.j256.ormlite.stmt.QueryBuilder;
import com.pda.ym.db.dao.ICarPlateTableDao;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.pda.ym.db.table.CarPlateTable;
import com.pda.uce.commom.util.LogUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * 车牌号数据操作类
 *
 * @author 000432
 * @date 2018/6/6 0006
 */
@Route(path = Constants.YM_CAR_PLATE_NO_IMPL)
public class CarPlateTableDao extends BaseDao<CarPlateTable, Long> implements ICarPlateTableDao {

    public CarPlateTableDao() {
        super(DbHelper.getInstance(BaseApplication.getContext()), CarPlateTable.class);
    }

    public void createOrUpdate(List<CarPlateTable> list) {
        SQLiteDatabase database = getDbHelper().getWritableDatabase();
        String tableName = dao.getTableName();
        StringBuffer sql = new StringBuffer("replace into ");
        sql.append(tableName);
        sql.append("(plateId,");
        sql.append("carPlate,");
        sql.append("useCount)");
        sql.append("values(?,?,?)");
        LogUtil.e("sql=" + sql.toString());

        database.beginTransaction();
        for (CarPlateTable item : list) {
            Object[] values = new Object[]{
                    item.getPlateId(), item.getCarPlate(), item.getUseCount()
            };
            database.execSQL(sql.toString(), values);
        }
        database.setTransactionSuccessful();
        database.endTransaction();
    }

    /**
     * 获取数据，根据使用次数倒序排序
     */
    @Override
    public List<CarPlateTable> getAllData() {
        try {
            QueryBuilder<CarPlateTable, Long> queryBuilder = dao.queryBuilder();
            List<CarPlateTable> lists = queryBuilder.orderBy("useCount", false).query();
            return lists;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int update(CarPlateTable entity) {
        try {
            return super.update(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public void init(Context context) {

    }
}
